package com.sg.business.model.bpmservice;

import java.util.HashMap;
import java.util.Map;

import org.bson.types.ObjectId;

import com.mobnut.db.model.ModelService;
import com.mobnut.db.model.PrimaryObject;
import com.mongodb.DBObject;
import com.sg.bpm.service.task.ServiceProvider;
import com.sg.bpm.workflow.utils.WorkflowUtils;
import com.sg.business.model.Project;
import com.sg.business.model.Work;

public class ProjectLifecycleService extends ServiceProvider {

	@Override
	public Map<String, Object> run(Object parameter) {
		HashMap<String, Object> result = new HashMap<String, Object>();

		Object content = getInputValue("content"); //$NON-NLS-1$
		Object project_id = getInputValue("project_id");
		if (project_id != null) {
			if (content instanceof String) {
				String jsonContent = (String) content;
				PrimaryObject host = WorkflowUtils.getHostFromJSON(jsonContent);
				if (host instanceof Work) {
					ObjectId _id = new ObjectId((String) project_id);
					Project project = ModelService.createModelObject(
							Project.class, _id);
					if (project != null) {
						try {
							DBObject processData = WorkflowUtils
									.getProcessInfoFromJSON(jsonContent);
							String processId = (String) processData
									.get("processId"); //$NON-NLS-1$
							String processName = (String) processData
									.get("processName"); //$NON-NLS-1$
							String lc = project.getLifecycleStatus();
							if (lc == null
									|| Project.STATUS_NONE_VALUE.equals(lc)) {
								project.doReady(new BPMServiceContext(
										processName, processId));
							}
						} catch (Exception e) {
							result.put("returnCode", "ERROR"); //$NON-NLS-1$ //$NON-NLS-2$
							result.put("returnMessage", e.getMessage()); //$NON-NLS-1$
						}
					}
				}
			}
		}
		return result;
	}
}
